package com.jky.trial.service.impl;

import com.jky.trial.common.BaseResult;
import com.jky.trial.common.ListResult;
import com.jky.trial.common.Pagination;
import com.jky.trial.common.jpush.JPushUtils;
import com.jky.trial.constant.DataStatus;
import com.jky.trial.entity.Project;
import com.jky.trial.entity.Task;
import com.jky.trial.entity.TaskExample;
import com.jky.trial.entity.User;
import com.jky.trial.mapper.TaskMapper;
import com.jky.trial.service.*;
import com.jky.trial.vo.TaskSampleVo;
import com.jky.trial.vo.TaskVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
    private final TaskMapper recordMapper;
    private final MsgService msgService;
    private final UserService userService;
    private final ProjectService projectService;
    private final TaskSampleService taskSampleService;

    @Autowired
    TaskServiceImpl(
            TaskSampleService taskSampleService,
            TaskMapper recordMapper,
            UserService userService,
            MsgService msgService,
            ProjectService projectService
    ) {
        this.taskSampleService = taskSampleService;
        this.msgService = msgService;
        this.userService = userService;
        this.recordMapper = recordMapper;
        this.projectService = projectService;
    }

    @Override
    public BaseResult importTask(List<Task> list) {
        int projectId = 0;
        for (int i = 0; i < list.size(); i++) {
            Task task = list.get(i);
            TaskExample taskExample = new TaskExample();
            TaskExample.Criteria ca = taskExample.createCriteria();
            ca.andNoEqualTo(task.getNo());
            ca.andDeletedEqualTo(false);
            ca.andProjectIdEqualTo(task.getProjectId());
            if (projectId == 0) projectId = task.getProjectId();//
            int count = (int) recordMapper.countByExample(taskExample);
            if (count > 0) {
                List<Task> listOne = recordMapper.selectByExample(taskExample);
                task.setId(listOne.get(0).getId());
                recordMapper.updateByExample(task, taskExample);
            } else {
                recordMapper.insertSelective(task);
            }
        }
        if (projectId != 0) {
            projectService.updateProgress(projectId);
        }
        return new BaseResult(true, 1);
    }

    @Override
    public BaseResult create(Task record) {

        record.setCreateAt(new Date());
        TaskExample example = new TaskExample();
        TaskExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(record.getName());
        criteria.andDeletedEqualTo(false);//
        List<Task> list = recordMapper.selectByExample(example);
        if (list.size() != 0) {
            return new BaseResult(false, "该勘察点名称已经存在，不能重复添加");
        }
        TaskExample example1 = new TaskExample();
        TaskExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andNoEqualTo(record.getNo());
        criteria1.andDeletedEqualTo(false);//
        List<Task> list1 = recordMapper.selectByExample(example1);
        if (list1.size() != 0) {
            return new BaseResult(false, "勘察点编号重复");
        }

        record.setCreateAt(new Date());
        recordMapper.insertSelective(record);
        return new BaseResult(true, record);
    }

    @Override
    public int assign(Task record, User user) {
        record.setSender(user.getId());
        record.setStatus(DataStatus.TASK_STATUS_DESC.getVal());
        record.setAssignAt(new Date());
        int res = update(record);
        //消息
        if (res > 0) {
            String content = "技术负责人" + user.getName() + "为您分配一个勘探点,请及时查看";
            msgService.sendMsg(
                    //  DataStatus.MSG_SENDER_SYSTEM.getVal(),
                    user.getId(),
                    record.getAssigneeId(),
                    content,
                    record.getId(),     //
                    DataStatus.MSG_TYPE_ASSIGN.getVal()
            );
            User descer = userService.detail(record.getAssigneeId());
            if (descer.getDescRegId() != null) {
                //推送通知
                JPushUtils.sendPush(descer.getDescRegId(), "分配消息", content);
            }

        }

        //推送通知
        return res;
    }

    @Override
    public int check(Task record, User user) {
        Task task = this.detail(record.getId());
        String reason = record.getDesc();
        record.setDesc(null);
        //任务不是审核通过、驳回状态或任务当前状态不是待验收状态，终止执行程序
        if ((!DataStatus.TASK_STATUS_RESOLVE.getVal().equals(record.getStatus()) &&
                !DataStatus.TASK_STATUS_REJECTED.getVal().equals(record.getStatus())) ||
                (!DataStatus.TASK_STATUS_SUBMIT.getVal().equals(task.getStatus()))
        ) { //
            return 0;//
        }


        int res = update(record);


        String action = DataStatus.TASK_STATUS_RESOLVE.getVal().equals(record.getStatus()) ? "验收通过" : "驳回";

        //消息
        if (res > 0) {
            String content = "技术员" + user.getName() + action + "您编号为" + task.getNo() + "的勘探点描述，意见\"" +
                    reason
                    + "\"，请及时修改重新提交!";
            if (DataStatus.TASK_STATUS_RESOLVE.getVal().equals(record.getStatus())) { //审核通过时，样品置为待提交状态
                TaskSampleVo taskSample = new TaskSampleVo();
                taskSample.setTaskId(task.getId());
                taskSample.setSize(Integer.MAX_VALUE);
                List<TaskSampleVo> list = taskSampleService.list(taskSample);
                list.forEach(item -> {
                    item.setStatus(DataStatus.TASK_SAMPLE_STATUS_NEED_SUBMIT.getVal());
                    taskSampleService.update(item);
                });
                content = "技术员" + user.getName() + action + "您编号为" + task.getNo() + "的勘探点描述，意见\"" +
                        reason
                        + "\"。";
            }
            msgService.sendMsg(
                    user.getId(),               //技术负责人
                    task.getAssigneeId(),       //描述员
                    content,
                    record.getId(),     ///
                    DataStatus.MSG_TYPE_CHECK_DESC.getVal()
            );
            User descer = userService.detail(task.getAssigneeId());
            if (descer.getDescRegId() != null) {
                //推送通知
                JPushUtils.sendPush(descer.getDescRegId(), "描述审核", content);
            }

        }
        return res;
    }

    @Transactional
    @Override
    public int submit(Task record, User user) {
        Task task = this.detail(record.getId());
        if (DataStatus.TASK_STATUS_SUBMIT.getVal().equals(task.getStatus())) {
            return 0;//
        }

        record.setStatus(DataStatus.TASK_STATUS_SUBMIT.getVal());
        int res = update(record);
        //消息
        if (res > 0) {
            Project project = projectService.detail(task.getProjectId());
            String content = "描述员" + user.getName() +
                    (task.getStatus().equals(DataStatus.TASK_STATUS_REJECTED) ? "重新" : "")
                    + "提交了一个勘探点描述，请及时查看验收!";
            //projectId
            msgService.sendMsg(
                    user.getId(),               //描述员
                    project.getTechDirector(),  //发送给当前技术负责人
                    content,
                    record.getId(),     ///
                    DataStatus.MSG_TYPE_SUBMIT_DESC.getVal()
            );
            User descer = userService.detail(project.getTechDirector());
            if (descer.getTechRegId() != null) {
                JPushUtils.sendPush(descer.getTechRegId(), "描述提交", content);
            }

        }


        return res;
    }

    @Override
    public int update(Task record) {

        return recordMapper.updateByPrimaryKeySelective(record);
    }



    @Override
    public int del(int id) {
        Task task = new Task();
        task.setId(id);
        task.setDeleted(true);//
        return recordMapper.updateByPrimaryKey(task);
    }

    @Override
    public TaskVo detail(int id) {

        TaskVo task = recordMapper.selectByPrimaryKey(id);
        if (task.getCreatorId() != null) { //创建用户
            User user = userService.detail(task.getCreatorId());
            task.setCreatorName(user.getName());
        }
        return task;
    }

    @Override
    public TaskVo moreDetail(int id) {
        TaskVo task = recordMapper.selectByPrimaryKey(id);

        if (task.getCreatorId() != null) {//描述员
            User user = userService.detail(task.getCreatorId());
            task.setCreatorName(user.getName());
        }
        if (task.getAssigneeId() != null) {//分配用户
            User user = userService.detail(task.getAssigneeId());
            task.setAssigneeName(user.getName());
        }
        if (task.getSender() != null) {//
            User user = userService.detail(task.getSender());
            task.setSenderName(user.getName());
        }
        if (task.getProjectId() != null) {//项目
            Project project = projectService.detail(task.getProjectId());
            task.setProjectName(project.getName());
        }
        return task;
    }

    @Override
    public List<TaskVo> list(TaskVo record) {
        return recordMapper.pageList(record);
    }

    @Override
    public List<TaskVo> msyList(TaskVo record) {
        return recordMapper.msyPageList(record);
    }

    public List<TaskVo> msyWithProjectNameList(TaskVo record) {
        return recordMapper.msyWithProjectNameList(record);
    }

    @Override
    public BaseResult mapData(TaskVo record) {
        Map map = new HashMap();
        record.setDeleted(false);
        record.setSize(300);
        List<TaskVo> list = list(record);
        map.put("tasks", list);
        map.put("project", projectService.moreDetail(record.getProjectId()));
        return new BaseResult(true, map);
    }

    /**
     * 按项目ID勘察点
     *
     * @param record
     * @return
     */
    @Override
    public ListResult page(TaskVo record) {

        record.setDeleted(false);
        if (record.getProjectId() == 0) {
            record.setProjectId(null);
        }
        List<TaskVo> list = list(record);
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                recordMapper.pageCount(record),
                record.getSize()
        ));
        return res;
    }

    @Override
    public ListResult msyPage(TaskVo record) {
        record.setDeleted(false);
        List<TaskVo> list = msyList(record);
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                (int) mysCount(record),
                record.getSize()
        ));
        return res;
    }

    public ListResult msyWidthProjectNamePage(TaskVo record) {
        record.setDeleted(false);
        List<TaskVo> list = msyWithProjectNameList(record);
        ListResult res = new ListResult(true, list);
        res.setPage(new Pagination(
                record.getPage(),
                (int) recordMapper.msyWithProjectNameCount(record),
                record.getSize()
        ));
        return res;
    }

    @Override
    public long mysCount(Task record) {
        TaskExample recordExample = new TaskExample();
        TaskExample.Criteria criteria = recordExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andAssigneeIdEqualTo(record.getAssigneeId());
        if (record.getSearch() != null) { //按名称搜索
            criteria.andNoLike("%" + record.getSearch());
        }
        if (record.getStatus() != null) { //按状态筛选
            criteria.andStatusEqualTo(record.getStatus());
        }
        if (record.getProjectId() != null) {
            criteria.andProjectIdEqualTo(record.getProjectId());
        }
        return recordMapper.countByExample(recordExample);
    }

    @Override
    public long count(Task record) {
        TaskExample recordExample = new TaskExample();
        TaskExample.Criteria criteria = recordExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (record.getSearch() != null) { //按名称搜索
            criteria.andNameLike(record.getSearch());
            criteria.andNoLike(record.getSearch());
        }
        if (record.getProjectId() != null) {
            criteria.andProjectIdEqualTo(record.getProjectId());
        }
        if (record.getStatus() != null) { //按状态筛选
            criteria.andStatusEqualTo(record.getStatus());
        }
        return recordMapper.countByExample(recordExample);
    }
}
